#!/bin/bash

if test "$1" != "start"
then
  exit 0
fi

source /recalbox/scripts/recalbox-includes.sh

do_boot_upgrade() {
    BOOTTAR=$1

    # all these files doesn't exist on non rpi platform, so, we have to test them
    BOOTFILES="cmdline.txt config.txt recalbox-boot.conf"

    # backup files to keep
    for BOOTFILE in ${BOOTFILES}
    do
	if test -e "/boot/${BOOTFILE}"
	then
	    cp "/boot/${BOOTFILE}" "/boot/${BOOTFILE}.upgrade" || return 1
	fi
    done

    # upgrade the boot
    if ! (cd /boot && xz -dc < "${BOOTTAR}" | tar mxvf - --no-same-owner >> /tmp/upgrade.files)
    then
	return 1
    fi

    # revert backup files
    for BOOTFILE in ${BOOTFILES}
    do
	if test -e "/boot/${BOOTFILE}.upgrade"
	then
	    mv "/boot/${BOOTFILE}.upgrade" "/boot/${BOOTFILE}" || return 1
	fi
    done
}

do_upgrade() {
    BOOTTAR="/recalbox/share/system/upgrade/boot.tar.xz"
    ROOTTAR="/recalbox/share/system/upgrade/root.tar.xz"
    NB_FILES_TARGET=`cat /recalbox/share/system/upgrade/root.list | wc -l`

    cp /bin/busybox /tmp
    # percentage
    touch /tmp/upgrade.files
    (
	echo "title Upgrading the system"
	while true
	do
	    NF=$(/tmp/busybox cat /tmp/upgrade.files | /tmp/busybox wc -l)
	    let NP=${NF}00/${NB_FILES_TARGET}
	    /tmp/busybox echo "percent ${NP}"
	    /tmp/busybox sleep 10
	done
    ) | /recalbox/scripts/shell2fb.py &

    # /boot is already upgraded
    # upgrading /root
    EXIT_CODE=1
    date
    echo "Upgrading /"
    # root.tar.xz does have a /boot entry, so mount RW /boot to prevent any error
    if mount -o remount,rw / && mount -o remount,rw /boot
    then
	if (cd / && \
	    cp ./etc/fstab ./etc/fstab.upgrade && \
	    xz -dc < "${ROOTTAR}" | tar mxvf - --no-same-owner >> /tmp/upgrade.files && \
	    mv ./etc/fstab.upgrade ./etc/fstab)
	then
	    EXIT_CODE=0
	fi
	sync
    fi
    test "${EXIT_CODE}" = 1 && return 1 # don't insist if /root failed to upgrade

    echo "Upgrade ended successfully."
    date
    return 0
}

pre_reboot_actions() {
  # If we don't restore before reboot, default values will be saved at reboot, losing custom ones
  recallog "Restoring sound config before reboot"
  alsactl -f /recalbox/share/system/configs/asound.state restore 2>&1 | recallog
  recallog "Upgrading RA Core names"
  upgradeRetroarchCoreNames -f /recalbox/share/system/configs/retroarch.corenames 2>&1 | recallog
  recallog "Reset case"
  sed -i 's/^case=.*$/d' /boot/recalbox-boot.conf
}

# what about doing an upgrade ?
if [ -e "/recalbox/share/system/upgrade/okforupgrade.go" ]
then
    # let's go
    do_upgrade > /recalbox/share/system/upgrade/upgrade.out.log 2> /recalbox/share/system/upgrade/upgrade.err.log && \
      find /lib/modules/ ! -name "`uname -r`" -maxdepth 1 -mindepth 1 -exec rm -rf {} \;
    # remove existing previous kernel modules, remember that new /lib/modules was added before reboot

    # remove to not apply it indefinitly, even if it fails
    rm "/recalbox/share/system/upgrade/boot.tar.xz" "/recalbox/share/system/upgrade/root.tar.xz" "/recalbox/share/system/upgrade/okforupgrade.go"

    # Last commands before reboot
    pre_reboot_actions
    # rebooting now
    shutdown -r now
fi

# share upgrade, just unzip share.zip from upgrade, no need to reboot
if test -e "/recalbox/share/system/upgrade/share.zip"
then
    (cd /recalbox/share && unzip -o /recalbox/share/system/upgrade/share.zip) > /recalbox/share/system/upgrade/upgrade.share.out.log 2> /recalbox/share/system/upgrade/upgrade.share.err.log
    # always remove to not apply indefinitly
    rm -f /recalbox/share/system/upgrade/share.zip
fi
